package com.taotao.content.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.taotao.common.pojo.EasyUITreeNode;
import com.taotao.common.pojo.TaotaoResult;
import com.taotao.content.service.ContentCategoryService;
import com.taotao.mapper.TbContentCategoryMapper;
import com.taotao.pojo.TbContentCategory;
import com.taotao.pojo.TbContentCategoryExample;
@Service
public class ContentCategoryServiceImpl implements ContentCategoryService {

	@Autowired
	public TbContentCategoryMapper contentCategoryMapper;
	
	@Override
	public List<EasyUITreeNode> getContentCategoryList(long parentId) {
		TbContentCategoryExample example = new TbContentCategoryExample();
		example.createCriteria().andParentIdEqualTo(parentId);
		
		List<TbContentCategory> contentCategories = contentCategoryMapper.selectByExample(example);
		List<EasyUITreeNode> result = new ArrayList<>();
		for (TbContentCategory tbContentCategory : contentCategories) {
			EasyUITreeNode treeNode = new EasyUITreeNode();
			treeNode.setId(tbContentCategory.getId());
			treeNode.setText(tbContentCategory.getName());
			treeNode.setState(tbContentCategory.getIsParent()?"closed":"open");
			result.add(treeNode);
		}
		return result;
	}

	/**
	 * 新增内容分类
	 */
	@Override
	public TaotaoResult saveContentCategory(TbContentCategory contentCategory) {
		//1、补全其他的属性
		contentCategory.setCreated(new Date());
		contentCategory.setIsParent(false);
		contentCategory.setSortOrder(1);
		//正常1，删除2
		contentCategory.setStatus(1);
		contentCategory.setUpdated(contentCategory.getCreated());
		//2、看情况更新父节点（如果父节点原先是叶子节点，需更新成非叶子节点）
		TbContentCategory parentContentCategory = contentCategoryMapper.selectByPrimaryKey(contentCategory.getParentId());
		if (!parentContentCategory.getIsParent()) {
			parentContentCategory.setIsParent(true);
			contentCategoryMapper.updateByPrimaryKeySelective(parentContentCategory);
		}
		contentCategoryMapper.insertSelective(contentCategory);
		//设置主键返回
		return TaotaoResult.ok(contentCategory.getId());
	}

}
